package com.slipper.codeless.resolve.support;

import com.slipper.codeless.resolve.query.QueryField;
import com.slipper.constants.Constants;
import com.slipper.util.DatabaseUtil;
import com.slipper.util.Tool;

import java.util.Arrays;
import java.util.stream.Collectors;

public class SqlserverSqlBuilder extends CommonSqlBuilder {
    @Override
    public String getSymbol() {
        return DatabaseUtil.getSymbol(Constants.Database.SQLSERVER);
    }

    @Override
    public String parseQueryField(String prefix, QueryField queryField) {
        if (Tool.isNotBlank(queryField.getTplContent())) {
            return queryField.getTplContent().replace("${value}", prefix + wrapSymbol(queryField.getOriginName()));
        } else if (queryField.getConcatName() == null || queryField.getConcatName().length == 0) {
            return prefix + wrapSymbol(queryField.getOriginName());
        } else {
            return "(" +
                    Arrays.stream(queryField.getConcatName())
                            .map(item -> prefix + wrapSymbol(item))
                            .collect(Collectors.joining(" + '" + queryField.getConcatSymbol() + "' + ")) +
                    ") as " + wrapSymbol(queryField.getOriginName());
        }
    }

    @Override
    public String getQueryRecursiveSql(String tableName, String pidName, String idName, String param) {
        String tempName = "tmp_" + Tool.getUUID();
        return "with recursive " + tempName + " as (" +
                "    select " + wrapSymbol(idName) + ", " + wrapSymbol(pidName) +
                "    from " + wrapSymbol(tableName) +
                "    where " + wrapSymbol(idName) + "=#{" + param + "}" +
                "    union all" +
                "    select t." + wrapSymbol(idName) + ", t." + wrapSymbol(pidName) +
                "    from " + wrapSymbol(tableName) + " t" +
                "        inner join " + tempName + " p on t." + wrapSymbol(pidName) + " = p." + wrapSymbol(idName) +
                ") select " + wrapSymbol(idName) + " from " + tempName;
    }

    @Override
    public String getQueryOrgLevelSql(String param) {
        return "with recursive tmp_organization_tree as (" +
                "    select id, parent_id from sys_organization where id = #{" + param + "}" +
                "    union all" +
                "    select o.id, o.parent_id from sys_organization o inner join tmp_organization_tree p on o.parent_id = p.id" +
                ") select id from tmp_organization_tree";
    }
}
